<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>{{ house.name if house else '房源详情' }}</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap.min.css') }}">
    <style>
        body { background-color:#f8f9fa; font-family:"微软雅黑",sans-serif; margin:0; padding:0; }
        .container-main { max-width:1000px; margin:30px auto; background:#fff; border-radius:8px; box-shadow:0 4px 20px rgba(0,0,0,0.06); overflow:hidden; }
        .house-header img { width:100%; height:420px; object-fit:cover; display:block; }
        .house-info { padding:20px; }
        .btn-area{ display:flex; gap:12px; margin-bottom:12px; align-items:center; }
        .btn { padding:8px 14px; border-radius:6px; cursor:pointer; text-decoration:none; }
        .btn-outline { border:1px solid #007bff; color:#007bff; background:transparent; }
        .btn-primary { background:#007bff; color:#fff; border:none; }
        .collection-btn { padding:6px 10px; border-radius:4px; border:1px solid #e0e0e0; background:#fff; cursor:pointer; }
        .collected { color:#e74c3c; border-color:#e74c3c; }
        .meta-row { display:flex; gap:16px; flex-wrap:wrap; margin-top:8px; color:#444; }
        .recommend-list { display:flex; gap:12px; flex-wrap:wrap; margin-top:12px; }
        .recommend-item img { width:160px; height:100px; object-fit:cover; border-radius:6px; }
    </style>
</head>
<body>
    <div class="container-main">
        <!-- 大图 -->
        <div class="house-header">
            <img src="{{ house.image_url }}" alt="{{ house.name }}">
        </div>

        <div class="house-info">
            <div class="btn-area">
                <button class="btn btn-outline" onclick="history.back();">← 返回上页</button>
                <a class="btn btn-primary" href="{{ url_for('index_page.index') }}">🏠 返回首页</a>

                <button id="collectBtn" class="collection-btn {% if collection %}collected{% endif %}" style="margin-left:12px;">
                    {% if collection %}♥ 已收藏{% else %}♡ 收藏{% endif %}
                </button>

                <span style="margin-left:auto; color:#888;">热度：{{ house.page_views if house.page_views is defined else '—' }}</span>
            </div>

            <h2>{{ house.name }}</h2>
            <div class="meta-row">
                <div><strong>价格：</strong><span style="color:#e74c3c;">{{ house.price }}</span></div>
                <div><strong>位置：</strong>{{ house.address }}</div>
                <div><strong>户型：</strong>{{ house.rooms }}</div>
                <div><strong>面积：</strong>{{ house.area }} 平米</div>
            </div>

            <hr>
            <p><strong>房源描述：</strong></p>
            <p>{{ house.description or '暂无描述' }}</p>

            <hr>
            <p><strong>配套设施：</strong></p>
            <ul>
                {% for f in facilities %}
                    <li>{{ f }}</li>
                {% endfor %}
            </ul>

            <hr>
            <h4>为你推荐的相似房源</h4>
            <div class="recommend-list">
                {% for r in recommend %}
                <div class="recommend-item">
                    <a href="{{ url_for('detail_page.index', hid=r.id) }}">
                        {% if r.image and r.image.startswith('http') %}
                            <img src="{{ r.image }}" alt="{{ r.address }}">
                        {% else %}
                            {% set rname = r.image if r.image else '' %}
                            {% set rsrc = (url_for('static', filename='uploads/' ~ rname) if rname else url_for('static', filename='img/house-bg1.jpg')) %}
                            <img src="{{ rsrc }}" alt="{{ r.address }}" onerror="this.onerror=null;this.src='{{ url_for('static', filename='img/house-bg1.jpg') }}'">
                        {% endif %}
                    </a>
                </div>
                {% endfor %}
            </div>

            <!-- ========== 房源数据分析（插入点） ========== -->
            <hr>
            <h4>房源数据分析</h4>
            <div id="analytics-panel" class="mb-4">
                <div style="display:flex; gap:20px; flex-wrap:wrap;">
                    <div style="flex:1 1 600px; min-width:300px;">
                        <h5>浏览量（最近 {{ config.ANALYTICS_DAYS or 30 }} 天）</h5>
                        <canvas id="viewsChart" width="800" height="300"></canvas>
                    </div>
                    <div style="width:320px;">
                        <h5>关键指标</h5>
                        <ul class="list-group">
                            <li class="list-group-item">总浏览量： <strong id="totalViews">—</strong></li>
                            <li class="list-group-item">近7天浏览： <strong id="last7">—</strong></li>
                            <li class="list-group-item">同地址排行： <strong id="rankRegion">—</strong></li>
                            <li class="list-group-item">当前价格： <strong id="curPrice">—</strong></li>
                            <li class="list-group-item">小区中位价： <strong id="commMedian">—</strong></li>
                            <li class="list-group-item">区域中位价： <strong id="regionMedian">—</strong></li>
                        </ul>
                    </div>
                </div>

                <div style="margin-top:18px;">
                    <h5>价格对比（当前房源 vs 小区/区域中位价）</h5>
                    <canvas id="priceBar" width="800" height="200"></canvas>
                </div>
            </div>
            <!-- ========== /房源数据分析 ========== -->

        </div>
    </div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
(function(){
    // 收藏按钮逻辑
    const collectBtn = document.getElementById('collectBtn');
    if (collectBtn) {
        collectBtn.addEventListener('click', function(){
            fetch('{{ url_for("detail_page.toggle_collect", hid=house.id) }}', {
                method: 'POST',
                headers: {'Content-Type':'application/json', 'X-Requested-With':'XMLHttpRequest'},
                body: JSON.stringify({})
            }).then(r=>r.json()).then(data=>{
                if(data && data.code==1){
                    if(data.collected){
                        collectBtn.classList.add('collected');
                        collectBtn.innerText = '♥ 已收藏';
                    } else {
                        collectBtn.classList.remove('collected');
                        collectBtn.innerText = '♡ 收藏';
                    }
                } else if(data && data.code==0 && data.msg){
                    alert(data.msg);
                } else {
                    console.warn('collect response', data);
                }
            }).catch(err=>{
                console.error(err);
                alert('收藏操作失败');
            });
        });
    }

    // Analytics 渲染
    const hid = {{ house.id }};
    const analyticsUrl = `/house/${hid}/analytics`;

    function numberOrDash(v){ return (v === null || v === undefined) ? '—' : v; }

    fetch(analyticsUrl)
    .then(r => r.json())
    .then(res => {
        if(!res || res.status !== 'ok'){ console.error('analytics error', res); return; }
        const data = res.data || {};
        const timeseries = data.timeseries || [];

        const labels = timeseries.map(t => t.date);
        const points = timeseries.map(t => t.views);

        // update summary
        document.getElementById('totalViews').innerText = numberOrDash(data.summary.total_views);
        document.getElementById('last7').innerText = numberOrDash(data.summary.last_7_days);
        document.getElementById('rankRegion').innerText = numberOrDash(data.summary.rank_in_region);
        document.getElementById('curPrice').innerText = numberOrDash(data.price_compare.current_price);
        document.getElementById('commMedian').innerText = numberOrDash(data.price_compare.community_median);
        document.getElementById('regionMedian').innerText = numberOrDash(data.price_compare.region_median);

        // Views line chart
        const ctx = document.getElementById('viewsChart').getContext('2d');
        new Chart(ctx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [{
                    label: '每日浏览量',
                    data: points,
                    fill: true,
                    tension: 0.3,
                    borderWidth: 2,
                    pointRadius: 2
                }]
            },
            options: { responsive: true, plugins: { legend: { display: false } } }
        });

        // Price bar chart
        const priceCtx = document.getElementById('priceBar').getContext('2d');
        const cur = data.price_compare.current_price || 0;
        const comm = data.price_compare.community_median || 0;
        const region = data.price_compare.region_median || 0;
        new Chart(priceCtx, {
            type: 'bar',
            data: {
                labels: ['当前', '小区中位', '区域中位'],
                datasets: [{ label: '价格 (元)', data: [cur, comm, region], borderWidth: 1 }]
            },
            options: { responsive: true, scales: { y: { beginAtZero: true } }, plugins: { legend: { display: false } } }
        });

    }).catch(err => {
        console.error('fetch analytics failed', err);
    });

})();
</script>
</body>
</html>
